package com.bw.android.bwgao6week2a.fragment;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.UriUtils;
import com.bw.android.bwgao6week2a.AppInstance;
import com.bw.android.bwgao6week2a.LiveActivity;
import com.bw.android.bwgao6week2a.R;
import com.bw.android.bwgao6week2a.RegisterActivity;
import com.bw.android.bwgao6week2a.databinding.FragmentPrepareLiveBinding;
import com.bw.android.bwgao6week2a.vm.PrepareLiveViewModel;
import com.bw.android.network.RequestClient;
import com.bw.android.network.bean.LoginReqBean;
import com.bw.ch.baselib.BaseBindingFragment;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class PrepareLiveFragment extends BaseBindingFragment<FragmentPrepareLiveBinding> {
    private PrepareLiveViewModel mPrepareModel;
    private MultipartBody.Companion companion;

    public PrepareLiveFragment() {
        super(true);
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_prepare_live;
    }

    @Override
    public void initView() {
        Log.d(AppInstance.TAG, "直播Fragment initView");
        mPrepareModel = new ViewModelProvider(this).get(PrepareLiveViewModel.class);
        mBinding.setPrepareModel(mPrepareModel);
        //监听是否选定封面图片
        mPrepareModel.liveCoverFile.observe(this, new Observer<File>() {
            @Override
            public void onChanged(File file) {
                Bitmap bitmap = ImageUtils.getBitmap(file);
                mBinding.ivLiveCover.setImageBitmap(bitmap);
            }
        });
        mBinding.btnRegister.setOnClickListener(v -> {
            startActivity(new Intent(this.getContext(), RegisterActivity.class));
        });
        //登录
        mBinding.btnLogin.setOnClickListener(v -> {
            LoginReqBean reqBean = new LoginReqBean();
            reqBean.userName = "ch";
            reqBean.passwd = "a123456";
            //请求直播登录的API
            RequestClient.buildService().liveLogin(reqBean)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(loginBean -> {
                        if (loginBean.getStatus().equalsIgnoreCase("0000")) {
                            //将登录成功后的数据保存到【AppInstance.loginResultBean】，用于后续开启直播时获取【uerId】,【sessionId】
                            AppInstance.getInstance().loginResultBean = loginBean.getResult();
                            Toast.makeText(PrepareLiveFragment.this.getContext(), "登陆成功", Toast.LENGTH_SHORT).show();
                        } else  {
                            AppInstance.getInstance().loginResultBean = null;
                            Toast.makeText(PrepareLiveFragment.this.getContext(), "登陆失败，code="+loginBean.getStatus(), Toast.LENGTH_SHORT).show();
                        }
                    }, throwable -> {
                        Toast.makeText(PrepareLiveFragment.this.getContext(), throwable.toString(), Toast.LENGTH_SHORT).show();
                    });
        });

        //选择封面
        mBinding.btnPickImg.setOnClickListener(v -> {
            //打开系统相册选择封面
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent,1);
        });

        //关闭开播
        mBinding.btnCloseLive.setOnClickListener(v -> {
            final int userId = AppInstance.getInstance().getUserId();
            final String sessionId = AppInstance.getInstance().loginResultBean.getSessionId();
            //若因为异常退出等原因，未关闭先前打开的直播，可调用此方法先关闭直播。
            RequestClient.buildService().closeLive(userId, sessionId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(closeLiveBean -> {
                        Toast.makeText(this.getContext(), closeLiveBean.message, Toast.LENGTH_SHORT).show();
                    }, throwable -> {
                        Toast.makeText(this.getContext(), throwable.toString(), Toast.LENGTH_SHORT).show();
                    });
        });

        //开播按钮
        mBinding.btnOpenLiveActivity.setOnClickListener(v -> {
            if(!validateUser()) {
                //校验失败，不能开播
                return;
            }
            //上传封面，需要要使用【multipart/form-data】
            RequestBody requestBody = RequestBody.create(MultipartBody.FORM, mPrepareModel.liveCoverFile.getValue());
            // 【liveCoverImage】是请求开播API中定义的参数名称
            MultipartBody.Part part = MultipartBody.Part.createFormData("liveCoverImage", mPrepareModel.liveCoverFile.getValue().getName(), requestBody);
            final int userId = AppInstance.getInstance().getUserId();
            final String sessionId = AppInstance.getInstance().loginResultBean.getSessionId();
            //请求 申请开启直播API
            RequestClient.buildService()
                    .openLive(
                            userId,
                            sessionId,
                            mPrepareModel.liveType.getValue(),
                            mPrepareModel.liveTitle.getValue(),
                            mPrepareModel.longitude.getValue(),
                            mPrepareModel.latitude.getValue(),
                            part
                    )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(openLiveBean -> {
                        System.out.println(openLiveBean.toString());
                        if (openLiveBean.getStatus().equalsIgnoreCase("0000")) {
                            LiveActivity.open(this.getContext(), openLiveBean.getLiveData());
                        } else {
                            //1001, 您有正在开启中的直播，请先关闭后再重新申请开启直播
                            Toast.makeText(this.getContext(), "请先关闭直播。status=" + openLiveBean.getStatus(), Toast.LENGTH_SHORT).show();
                        }
                    }, throwable -> {
                        System.out.println(throwable.toString());
                    });
        });

    }


    @Override
    public void initData() {

    }

    /**
     * 请求开播API前，先校验用户是否登录，以及是否设置了昵称和封面。
     */
    private boolean validateUser() {
        String errMsg = "";
        if (AppInstance.getInstance().getUserId() > 0 && AppInstance.getInstance().loginResultBean.getSessionId() != null) {
            if (!mPrepareModel.liveTitle.getValue().trim().isEmpty()) {
                if(mPrepareModel.liveCoverFile.getValue() != null) {
                    return true;
                } else {
                    errMsg = "请选择封面";
                }
            } else {
                errMsg = "请输入【直播标题】";
            }
        } else {
            errMsg = "用户未登录，请先登录。";
        }
        Toast.makeText(this.getContext(), errMsg, Toast.LENGTH_LONG).show();
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK){
            //打系统开相并选取图片后，设置封面并保存封面文件，用于后续上传封面
            File file = UriUtils.uri2File(data.getData());
            //保存封面文件
            mPrepareModel.liveCoverFile.setValue(file);
        }
    }

}